package com.ketai.common;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author:长沙科泰梦想学院
 * @Description:
 * @Date:Create In 2022/7/16 14:07
 **/

@WebServlet("/globalException")
public class ExceptionServlet extends HttpServlet {

    @Override
    protected void service (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("========================");
        // 获取到其他service层抛出来的异常信息  包括code 和message
        // Analyze the servlet exception
        KetaiException throwable = (KetaiException) req
                .getAttribute("javax.servlet.error.exception");
        Integer statusCode = throwable.getCode();
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write(JSON.toJSONString(Result.error(statusCode, throwable.getMessage())));

    }
}
